/**
 * vuex
 */
interface State{
    user:Object
}

interface UserData{
    email: string,
    token: string,
    username: string,
    image: string
}

const cookieparser = process.server ? require('cookieparser') : undefined

export const state = () => {
  return {
    user: null
  }
}

export const mutations = {
  setUser (state:State, data:UserData) {
    state.user = data
  }
}

export const actions = {
  // @ts-ignore: Unreachable code error
  nuxtServerInit ({ commit }, { req }) {
    let user = null
    if (req.headers.cookie) {
      const parsed = cookieparser.parse(req.headers.cookie)
      try {
        user = JSON.parse(parsed.user)
      } catch (err) {
        // No valid cookie found
      }
    }
    commit('setUser', user)
  }
}
